import { showToast, closeToast } from 'vant';

let loadingCount = 0; // 请求计数器
let timer = null;

const showLoading = () => {
  // 防抖处理：避免频繁显示/隐藏
  clearTimeout(timer);
  timer = setTimeout(() => {
    showToast({
      type: 'loading',
      message: 'loading...',
      duration: 0, // 持续展示
      forbidClick: true,
      overlay: true,
      className: 'custom-loading', // 自定义类名
    });
  }, 300); // 300ms 后显示，避免快速请求时闪烁
};

const hideLoading = () => {
  clearTimeout(timer);
  if (loadingCount > 0) return;
  closeToast();
};

export const startLoading = () => {
  loadingCount++;
  if (loadingCount === 1) showLoading();
};

export const endLoading = () => {
  loadingCount = Math.max(0, loadingCount - 1);
  if (loadingCount === 0) hideLoading();
};

export const resetLoading = () => {
  loadingCount = 0;
  hideLoading();
};